package com.qianfeng.gl4study.youshare.acitivity.store;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.*;
import com.qianfeng.gl4study.youshare.R;
import com.qianfeng.gl4study.youshare.adapters.CollectAdapter;
import com.qianfeng.gl4study.youshare.model.CollectItem;
import com.qianfeng.gl4study.youshare.model.Product;
import com.qianfeng.gl4study.youshare.tasks.CollectTask;
import com.qianfeng.gl4study.youshare.tasks.TaskProcessor;
import com.qianfeng.gl4study.youshare.utils.CollectDatabasesManager;
import com.qianfeng.gl4study.youshare.utils.Constants;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

/**
 * 购物车或收藏列表的显示，由于添加购物车接口存在问题，故，只能完成本地数据的操作
 * Created with IntelliJ IDEA.
 * I'm glad to share my knowledge with you all.
 * User:Gaolei
 * Date:2015/2/25
 * Email:pdsfgl@live.com
 */
public class CollectActivity extends Activity implements CompoundButton.OnCheckedChangeListener, View.OnClickListener, TaskProcessor {

	private LinkedList<CollectItem> data;
	private ListView collectListView;
	private CollectAdapter adapter;
	private TextView txtTotalFee;
	private Button checkout;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_collect);
		collectListView = (ListView) findViewById(R.id.collect_list_view);

		data = new LinkedList<CollectItem>();

		//由于接口原因，不在从网络获取用户购物车信息，仅操作本地数据即可。
		/*
		CollectTask collectTask = new CollectTask(this);
		collectTask.execute(Constants.USER_ID);
		*/

		CollectDatabasesManager databasesManager = CollectDatabasesManager.createInstance(this);
		data = databasesManager.getProductCollect(Constants.USER_ID);

		adapter = new CollectAdapter(this, data);

		adapter.setCheckedChangeListener(this);
		adapter.setOperationListener(this);

		collectListView.setAdapter(adapter);

		//全选按钮处理
		CheckBox selectAll = (CheckBox) findViewById(R.id.cart_select_all);
		txtTotalFee = (TextView) findViewById(R.id.cart_total_fee);
		checkout = (Button) findViewById(R.id.cart_checkout);
		selectAll.setOnCheckedChangeListener(this);
	}
	private void calcTotalFee(){
		float totalFee = 0;
		int totalCount = 0;
		for (CollectItem CollectItem : data) {
			if(CollectItem.isChecked()){
				float productPrice = CollectItem.getProductPrice();
				int count = CollectItem.getCount();
				totalFee += productPrice*count;
				totalCount+= count;
			}
		}
		txtTotalFee.setText("总金额：￥"+totalFee);
		checkout.setText("去结算（" + totalCount + "）");
	}
	@Override
	public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
		int id = buttonView.getId();
		if(id == R.id.item_cart_cheked){
			Object tag = buttonView.getTag();
			if(tag!=null&&tag instanceof Integer){
				int pos = (Integer) tag;
				CollectItem item = data.get(pos);
				int count = item.getCount();
				item.setChecked(isChecked);
				adapter.notifyDataSetChanged();
			}
		}else if(id == R.id.cart_select_all){
			//先修改数据，然后刷新
			for (CollectItem CollectItem : data) {        //遍历快捷键iter
				CollectItem.setChecked(isChecked);
			}
			adapter.notifyDataSetChanged();
		}
		calcTotalFee();
	}

	@Override
	public void onClick(View v) {
		int id = v.getId();
		Object tag = v.getTag();
		if(tag!=null&&tag instanceof Integer){
			int pos = (Integer) tag;
			CollectItem item = data.get(pos);
			int count = item.getCount();
			if(id == R.id.item_cart_sub) {  //点击减少
				if (count > 0) {
					item.setCount(count - 1);
				}
			}else if(id == R.id.item_cart_add){//点击增加
				item.setCount(count+1);
			}else if(id == R.id.item_cart_delete){
				data.remove(pos);
			}
			adapter.notifyDataSetChanged();
		}
		calcTotalFee();
	}

	@Override
	public void processResult(JSONObject result, int flag) {
		try {
			int code = result.getInt("code");
			//code为1，代表返回数据正确，msg是一个对象，若code不是1，代表数据请求失败，msg返回字符串
			if(code == 1){
				//数据正确，需要解析
				JSONObject msg = result.getJSONObject("msg");
				JSONArray goodsList = msg.getJSONArray("goods_list");
				for (int i = 0; i < goodsList.length(); i++) {
					JSONObject jsonObject = goodsList.getJSONObject(i);
					CollectItem collectItem = new CollectItem();
					collectItem.setProductName(jsonObject.getString("goods_name"));
					collectItem.setCount(Integer.parseInt(jsonObject.getString("goods_number")));
					collectItem.setProductId(jsonObject.getString("product_id"));
					String goodsPrice = jsonObject.getString("goods_price");
					//价格默认使用200
					collectItem.setProductPrice(200.0f);
					collectItem.setProductThumb(jsonObject.getString("goods_thumb"));
					data.add(collectItem);
				}

				adapter.notifyDataSetChanged();

			}else {
				//数据请求失败
				String msg = result.getString("msg");
				Toast.makeText(this, msg,Toast.LENGTH_LONG).show();
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}
}